package com.demo.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.demo.dto.R;
import com.demo.entity.User;
import com.demo.service.UserService;
import io.swagger.annotations.Api;

import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.Date;

/**
 * (User)表控制层
 *
 * @author Sakura
 * @since 2023-11-26 17:11:08
 */
@Api(value = "/api/user", tags = {"(User)表控制层"})
@RestController
@RequestMapping("/api/user")
@CrossOrigin
public class UserController {
/**
 * 服务对象
 */
@Resource
private UserService userService;

    @GetMapping("/list/{pageNo}/{pageSize}")
    public R list(@PathVariable Integer pageNo,
                  @PathVariable Integer pageSize,
                  @RequestParam(required = false) String searchKey) {
        LambdaQueryWrapper<User> userWrapper = new LambdaQueryWrapper<>();
        userWrapper.like(searchKey != null && searchKey != "", User::getName, searchKey);
        Page<User> page = userService.page(new Page<>(pageNo, pageSize), userWrapper);
        return R.success(page);
    }

    @PostMapping("saveOrUpdate")
    public R saveOrUpdate(@RequestBody User user) {

        //id为0则是添加
        if (user.getId()==null||user.getId() == 0) {
            user.setUpdateTime(new Date());
            user.setCreateTime(new Date());
            boolean save = userService.save(user);
            if (!save) {
                return R.error("添加失败");
            }
            return R.success("添加成功");
        }
        //修改
        user.setUpdateTime(new Date());
        boolean update = userService.updateById(user);
        if (!update) {
            return R.error("修改失败");
        }
        return R.success("修改成功");
    }

    @GetMapping("/detail/{uid}")
    public R userDetail(@PathVariable("uid") long uid) {
        User user = userService.getById(uid);

        return R.success(user);
    }

    @PostMapping("/detail/update")
    public R updateUserDetail(@RequestBody User user) {
        boolean update = userService.updateById(user);
        if (!update) {
            return R.error("修改失败");
        }
        return R.success("修改成功");
    }

    @DeleteMapping("/delete/{uid}")
    public R deleteUser(@PathVariable("uid") long uid) {
        boolean remove = userService.removeById(uid);
        if (!remove) {
            return R.error("删除失败，请重新尝试");
        }
        return R.success("删除成功");
    }

    @PutMapping("/resetPwd/{uid}")
    public R resetPwd(@PathVariable("uid") long uid){
        User user = userService.getById(uid);
        user.setPassword("123");
        boolean update = userService.updateById(user);
        if (!update){
            return R.error("重置失败，请重新尝试");
        }
        return R.success("重置成功");
    }
}
